package com.wyix;

import java.util.concurrent.Semaphore;

/**
 * @author wangdx
 * @since 2025/8/4
 */
public class SemaphoreDemo {
    public static void main(String[] args) {
        // 允许3个线程同时访问
        Semaphore semaphore = new Semaphore(3);

        for (int i = 0; i < 10; i++) {
            new Thread(() -> {
                try {
                    semaphore.acquire(); // 获取许可（无许可则阻塞）
                    System.out.println(Thread.currentThread().getName() + "访问资源");
                    Thread.sleep(1000); // 模拟资源访问
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                } finally {
                    semaphore.release(); // 释放许可
                }
            }, "wyix-" + i).start();
        }
    }
}